﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;

namespace Nok_Air
{
    public partial class Payment : PhoneApplicationPage
    {
        private System.Windows.Controls.Primitives.Popup popup;
        private string indexAvailabilityItemsPar = "";
        private string roundtripFlag = "";
        private string PassengerInfoPar = "";
        private int[] indexAvailabilityItems;
        private string[] sellingClass_indexAvailabilityItems;
        public Payment()
        {
            popup = new System.Windows.Controls.Primitives.Popup();
            popup.Child = new ProgressBarUserControl();
            InitializeComponent();
            DataContext = App.ViewModel;

            indexAvailabilityItems = new int[2];
            sellingClass_indexAvailabilityItems = new string[2];
            for (int aitemIndex = 0; aitemIndex < indexAvailabilityItems.Count(); aitemIndex++)
            {
                indexAvailabilityItems[aitemIndex] = -1;
                sellingClass_indexAvailabilityItems[aitemIndex] = "-1";
            }

            Nok_Air.WebService.NokAirServicesHelper nokSHelp = new Nok_Air.WebService.NokAirServicesHelper();
            nokSHelp.GetFees();
        }

        void nokSHelp_RequestCompleted(object sender, WebService.RequestCompletedEventArgs ev)
        {
            if (ev.exception != null)
            {
                Dispatcher.BeginInvoke(() =>
                {
                    MessageBox.Show("Connection Error");
                    NavigationService.GoBack();
                    NavigationService.Navigated += (ss, ee) => { popup.IsOpen = false; };
                });
                return;
            }
            Dispatcher.BeginInvoke(() => popup.IsOpen = false);
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationService.CanGoBack && App.ViewModel.IsFinishTransaction)
            {
                NavigationService.GoBack();
            }

            if (NavigationContext.QueryString.TryGetValue("indexAvailabilityItems", out indexAvailabilityItemsPar))
            {
                if (indexAvailabilityItemsPar.Contains(','))
                {
                    string[] tmpPar = indexAvailabilityItemsPar.Split(',').ToArray();
                    indexAvailabilityItems[0] = int.Parse(tmpPar[0].Split('_')[0]);
                    indexAvailabilityItems[1] = int.Parse(tmpPar[1].Split('_')[0]);
                    sellingClass_indexAvailabilityItems[0] = tmpPar[0].Split('_')[1];
                    sellingClass_indexAvailabilityItems[1] = tmpPar[1].Split('_')[1];
                }
                else {
                    indexAvailabilityItems[0] = int.Parse(indexAvailabilityItemsPar.Split('_')[0]);
                    sellingClass_indexAvailabilityItems[0] = indexAvailabilityItemsPar.Split('_')[1];
                }
            }

            //get PassengerInfo parameter.
            NavigationContext.QueryString.TryGetValue("PassengerInfo", out PassengerInfoPar);
            NavigationContext.QueryString.TryGetValue("roundtripFlag", out roundtripFlag);

        }   

        private void continueButton_Click(object sender, RoutedEventArgs e)
        {
            if (!yesRBT.IsChecked.Value && !atmRTB.IsChecked.Value && !csRTB.IsChecked.Value)
            {
                return;
            }
            else if (yesRBT.IsChecked.Value && (atmRTB.IsChecked.Value || csRTB.IsChecked.Value))
            {
                string PaymentTypePar = csRTB.IsChecked == true ? "CS" : "AT";
               // string deviceID = "674f50561dd2bfc6dd47604cc4711b57188281co";
                string deviceID = "";
                System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex("[^a-z0-9]");
                object uniqueId;
                if (Microsoft.Phone.Info.DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
                {
                    deviceID = rx.Replace(Convert.ToBase64String(((byte[])uniqueId)).ToLower(), "");

                    //UUID must be 40 char.
                    while (deviceID.Length < 40) { deviceID += "0"; }
                    //MessageBox.Show(deviceID);                   
                    Nok_Air.WebService.NokAirServicesHelper nokSHelp = new Nok_Air.WebService.NokAirServicesHelper();
                    nokSHelp.RegisterPaymentChannelCompleted += (s, ev) =>
                    {
                        Dispatcher.BeginInvoke(() =>
                        {
                            NavigationService.Navigate(new Uri("/BookFlight/4Report.xaml?indexAvailabilityItems=" + indexAvailabilityItemsPar + "&PassengerInfo=" + PassengerInfoPar + "&PaymentType=" + PaymentTypePar + "&RegisterId=" + deviceID + "&roundtripFlag=" + roundtripFlag, UriKind.Relative));
                            popup.IsOpen = false;
                        });
                    };
                    popup.IsOpen = true;
                    nokSHelp.RegisterPaymentChannel(deviceID, csRTB.IsChecked == true ? "711" : "ATM");
                }
            }
            else { return; }
        }
        private void PaymentMethod_Checked(object sender, System.Windows.RoutedEventArgs e)
        {
            RadioButton rd = sender as RadioButton;

           foreach(var _feeItem in App.ViewModel.FeeItem)
           {
               if (_feeItem.Code == rd.Tag.ToString()) {
                   FeeTBlock.Text = App.ViewModel.Fee + ": "+ _feeItem.Amount + App.ViewModel.MoneyUnit;
                   break;
               }
           }
        }
    }
}
